//------------------------------------------------------------------------------
#include "colorbutton.h"
#include <QDebug>
#include <QColorDialog>
#include <QPainter>
#include <QBrush>
#include <QPen>
//------------------------------------------------------------------------------
ColorButton::ColorButton(QWidget *parent) : QPushButton(parent){
	// Default selected color
	m_selectedColor = QColor("#000000");

	m_colorDialog = 0;

	this->setFlat(true);
	this->setAutoFillBackground(true);
	this->setAutoDefault(false);
	this->setDefault(false);

	connect(this, SIGNAL(released()), this, SLOT(mouseReleased()));
}
//------------------------------------------------------------------------------
ColorButton::~ColorButton(){}
//------------------------------------------------------------------------------
void ColorButton::mouseReleased(){
	if(!m_colorDialog){
		m_colorDialog = new QColorDialog(m_selectedColor, this);
		connect(m_colorDialog, SIGNAL(colorSelected(QColor)), this, SLOT(colorSelected(QColor)));
	}

	m_colorDialog->open();
}
//------------------------------------------------------------------------------
void ColorButton::colorSelected(const QColor &color){
	if(!color.isValid())
		return;

	m_selectedColor = color;

	this->update();

	if(m_colorDialog)
		m_colorDialog->setCurrentColor(color);

	emit selectedColorChanged(m_selectedColor);
}
//------------------------------------------------------------------------------
void ColorButton::paintEvent(QPaintEvent*){
	QPainter painter(this);
	painter.setBrush(QBrush(m_selectedColor));

	QPen pen(Qt::black);
	pen.setWidth(1);

	if(isEnabled() && underMouse())
		pen.setColor(m_selectedColor.lighter());

	painter.setPen(pen);
	painter.drawRect(0, 0, width()-1, height()-1);
}
//------------------------------------------------------------------------------
